<template>
  <div class="login-container">
    <van-nav-bar title="黑马头条-登录" fixed />
    <van-form @submit="onSubmit">
      <!-- label属性表示左侧描述 -->
      <van-field
        v-model="from.mobile"
        label="手机号码"
        placeholder="请输入手机号码"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: /^1\d{10}$/, message: '请输入正确手机号码' },
        ]"
      />
      <van-field
        v-model="from.code"
        type="password"
        label="登录密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <router-view> </router-view>
  </div>
</template>
<script>
import { loginAPI } from '@/api/userAPI.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      from: { mobile: '', code: '' }
    }
  },
  methods: {
    ...mapMutations(['updateTokenInfo']),
    async onSubmit () {
      // 获取到用户填写信息
      // 如果调用某个
      console.log(this.from)
      //  async 和await要一起使用
      const { data: res } = await loginAPI(this.from)
      console.log(res)
      if (res.message === 'OK') {
        // 证明登录成功
        // 把token存储到本地 要跳转到页面
        // localStorage.setItem('token', JSON.stringify(res.data))
        // 把token信息存储到vuex中
        this.updateTokenInfo(res.data)
        this.$router.push('/')
      }
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  padding-top: 46px;
  .van-nav-bar__title {
    color: white;
    font-size: 14px;
  }
}
</style>
